/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import GUI.JFrameBase;
import java.awt.Component;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import libraries.Application;
import model.DB2Hash;

/**
 *
 * @author aeguzkiza
 */
public class WorklistPanelView {
    
    private final JFrameBase frame;
    
    
    public WorklistPanelView(JFrameBase frame) {
        this.frame = frame;
    }
    
    public ArrayList<String> getWorklistFilters() {
        ArrayList<String> filters = new ArrayList();
        
        
        // Selected period:        
        String today = frame.parseDate(null);
        String lastWeek = frame.parseDate(Application.dateFromNow(-6));
        String dateInterval = "";
        if(frame.WorklistDate_Radio1.isSelected()){
            dateInterval = today; 
        }else if(frame.WorklistDate_Radio2.isSelected()){            
            dateInterval = lastWeek+"-"+today;  // Interval for DCM4CHEE is defined by '-'.
        }else if(frame.WorklistDate_Radio3.isSelected()){/*Do nothing.*/}
        
            
        String PatientId = "*"+frame.PatientIdInput_WF.getText()+"*";
        String PatientName = "*"+frame.PatientNameInput_WF.getText()+"*";
        String AccessNumber = "*"+frame.AccessNumberInput_WF.getText()+"*";
        String StudyDescription = "*"+frame.StudyDescriptionInput_WF.getText()+"*";
        
        //String dateInterval_tag = "00404005"; // Scheduled Procedure Start DateTime.
        String dateInterval_tag = "00400002"; // Scheduled Procedure Start Date.
        //String dateInterval_tag = "00321000"; // Scheduled Study Start Date. 
        
        filters.add(dateInterval_tag);
        filters.add(dateInterval);
        
        String PatientId_tag = "00100020";
        filters.add(PatientId_tag);
        filters.add(PatientId);
        
        String PatientName_tag = "00100010";
        filters.add(PatientName_tag);
        filters.add(PatientName);
        
        String AccessNumber_tag = "00080050";
        filters.add(AccessNumber_tag);
        filters.add(AccessNumber);
        
        String StudyDescription_tag = "00081030";
        filters.add(StudyDescription_tag);
        filters.add(StudyDescription);
        //System.out.println("dateInterval: "+dateInterval+"PatientId: "+PatientId+"PatientName: "+PatientName+"AccessNumber: "+AccessNumber);            
        return filters;
    }
     
    
    public DB2Hash getReferralNote() {
        DB2Hash referralNote = new DB2Hash();
                
        int XselectedRow = frame.WorklistXTable.getSelectedRow();
        
        for(int i=0; i<frame.WorklistXTable.getColumnCount();i++){
            
            //String columnName = frame.WorklistXTable.getColumnModel().getColumn(i).getHeaderValue().toString();
            DicomAttribute columnName = (DicomAttribute) frame.WorklistXTable.getColumnModel().getColumn(i).getHeaderValue();
            System.out.println("Column Names2: "+columnName);    // !!! Column names no cambia al mover columnas.
            
            
            DicomAttribute column = frame.columnNames.get(i); 
            System.out.println("Column Names: "+column);
            
            
            Object cellValue = frame.WorklistXTable.getValueAt(XselectedRow, i);
            
            if(cellValue != null){  // If the current cell is empty, it ignores it.
                String cellValue2String = cellValue.toString();
                referralNote.set(column.getDicomTag(), cellValue2String);          
            }
        }       
        
        return referralNote;
    }
    
    public void setReferralNote(ArrayList<String> referralNote) {   // Writes a new row in Worklist table.
        
        DefaultTableModel Xmodel = (DefaultTableModel) frame.WorklistXTable.getModel();
        Vector v = new Vector(referralNote);
        for(int j=0; j<=frame.WorklistXTable.getColumnCount();j++){   
            v.addElement(j);
        }       
        System.out.println("Vector a tabla worklist: "+v);
        Xmodel.addRow(v); 
    }
    
        
    public void updateViewWorklistTable(ArrayList<DB2Hash> referralNote){
       
            System.out.println();
            System.out.println("========== Start of updateViewWorklistTable ==========");
            
            ButtonHeaderRenderer renderer = new ButtonHeaderRenderer();  
            DefaultTableModel Xmodel = (DefaultTableModel) frame.WorklistXTable.getModel();   // Gets table default model.                
            
            //model.getDataVector().clear();  // Deletes every row from the table.         
            //model.getDataVector().removeAllElements();     
            //model.setColumnCount(0);    // Deletes columns.
            
            // Writes data on GUI WORKLIST TABLE cell by cell.
            Object [] filas = new Object[referralNote.size()];
            
            for(int i=0;i<referralNote.size();i++){
                DB2Hash attributes = referralNote.get(i);
                System.out.println("Attributes: "+attributes);
                                                
                int currentXColumn = Xmodel.getColumnCount();
                
                //JTableHeader header = frame.WorklistTable.getColumnName(i);                
                //System.out.println("Column index: "+frame.WorklistTable.getColumnModel().getColumnIndex("Sexo"));                
                //System.out.println("Column found: "+frame.WorklistTable.getColumnModel().getColumnIndex(attributes.get("AttributeName")));
                
                DicomAttribute dicomAttribute = new DicomAttribute(attributes.get("Tag"),attributes);
                
                try{
                    // There is a column name with these characteristics.                                        
                    TableColumnModel Xtcm = frame.WorklistXTable.getColumnModel();                    
                    int Xlocation = Xtcm.getColumnIndex( dicomAttribute.toString() );
                    filas[Xlocation] = attributes.get("AttributeValue");
                    TableColumn Xcolumn = Xtcm.getColumn( Xlocation );
                    //frame.WorklistXTable.getColumnModel().getColumn(Xlocation).setHeaderRenderer(renderer);
                    
                }catch(IllegalArgumentException e) {
                    // Case there's not a column for the current attribute, creates a new one. 
                    frame.columnNames.add(dicomAttribute);
                    
                    Xmodel.addColumn(dicomAttribute);   // Add column if there isn't on table.                     
                    filas[currentXColumn] = attributes.get("AttributeValue");
                }               
                System.out.println("AttributeValue: "+filas[i]);
                
                
                /*Enumeration miau = model.getDataVector().elements();
                System.out.println("MIAU:"+miau.nextElement());*/
                
                
                /*if(Integer.parseInt(attributes.get("Tag")) == 0x00080050){  // AccessionNumber
                    frame.WorklistTable.setValueAt(attributes.get("AttributeValue"), currentRow, 7);
                }*/         
                
                    
                /*String columnName = model.getColumnName(i);
                model.getColumnName(i);
                System.out.println("CurrentColumnName: "+columnName);                    
                
                frame.WorklistTable.setValueAt(attributes.get("AttributeValue"), currentRow, i);*/
                //int ColCount = frame.WorklistTable.getColumnCount();   // Gets table column number.
                                
            }
            Xmodel.addRow(filas);            
            //JTableHeader Xheader = frame.WorklistXTable.getTableHeader();
            //Xheader.addMouseListener(new HeaderListener(Xheader, renderer));
          
        
    }
    
    public void clearAll(){
        DefaultTableModel Xmodel = (DefaultTableModel) frame.WorklistXTable.getModel();   // Gets table default model. 
        Xmodel.getDataVector().clear();
        Xmodel.getDataVector().removeAllElements();        
        frame.WorklistXTable.setModel(Xmodel);  // Reload table after clearing all.
    }
    
    // Java Classes:
    class ButtonHeaderRenderer extends JButton implements TableCellRenderer {
        int pushedColumn;

        public ButtonHeaderRenderer() {
          pushedColumn = -1;
          setMargin(new Insets(0, 0, 0, 0));
        }

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
          setText((value == null) ? "" : value.toString());
          boolean isPressed = (column == pushedColumn);
          getModel().setPressed(isPressed);
          getModel().setArmed(isPressed);
          return this;
        }

        public void setPressedColumn(int col) {
          pushedColumn = col;
        }
    }
    class HeaderListener extends MouseAdapter {
    JTableHeader header;

    ButtonHeaderRenderer renderer;

    HeaderListener(JTableHeader header, ButtonHeaderRenderer renderer) {
      this.header = header;
      this.renderer = renderer;
    }

    
    
    
    /*public void mousePressed(MouseEvent e) {
      int col = header.columnAtPoint(e.getPoint());
      //System.out.println("Hidden! " + col);
      DicomAttribute moe = frame.columnNames.get(col);
      System.out.println("DicomAttribute: "+moe.getDicomAttribute().get("AttributeName"));
      
      renderer.setPressedColumn(col);
      header.repaint();
      
      String colName = frame.WorklistTable.getColumnName(col);      
      //frame.WorklistTable.getColumnExt(col).setVisible(false);                  
      
      /*frame.WorklistTable.getColumnModel().getColumn(col).setMaxWidth(0);
      frame.WorklistTable.getColumnModel().getColumn(col).setMinWidth(0);
      frame.WorklistTable.getColumnModel().getColumn(col).setPreferredWidth(0);   
      frame.WorklistTable.getColumn(colName).setMaxWidth(0);
      frame.WorklistTable.getColumn(colName).setMinWidth(0);
      frame.WorklistTable.getColumn(colName).setPreferredWidth(0);*/
      
    //}

    public void mouseReleased(MouseEvent e) {
      //frame.WorklistTable.getTableHeader().setVisible(false);   // Hide table header.
      
      // Hide column.
      /*int colIndex = header.columnAtPoint(e.getPoint());
      TableColumn colData = frame.WorklistTable.getColumnModel().getColumn(colIndex);
      //frame.WorklistTable.getColumnModel().removeColumn(colData); 
      
      // Show column.
      /*TableColumn col = getColumnObejct();
      frame.WorklistTable.getColumnModel().addColumn(col); //add it to the righmost side.
      frame.WorklistTable.getColumnModel().moveColumn(frame.WorklistTable.getColumnModel().getColumnCount()-1, colIndex);*/
      
      /*frame.WorklistTable.getColumnModel().getColumn(col).setMaxWidth(0);
      frame.WorklistTable.getColumnModel().getColumn(col).setMinWidth(0);
      frame.WorklistTable.getColumnModel().getColumn(col).setPreferredWidth(0);   */
      
      //renderer.setPressedColumn(-1); // clear
      //header.repaint();
    }
  }

}
